<template>
  <div class="transfer-records">
    <div class="record-header">
      <div class="tab-container">
          <div class="tab-item left" :class="{ active: downloadStatus === 'progress' }" @click="downloadStatus = 'progress'; handleStatusChange()">
            下载中（0）
          </div>
          <div class="tab-item right" :class="{ active: downloadStatus === 'finished' }" @click="downloadStatus = 'finished'; handleStatusChange()">
            已完成（9）
          </div>
      </div>
      <div class="action-buttons">
        <el-button class="batch-btn batch-start" size="small" @click="startAllDownloads" :disabled="!hasCheckedItems">
          <i class="el-icon-caret-right"></i> 批量开始
        </el-button>
        <el-button class="batch-btn batch-pause" size="small" @click="pauseAllDownloads" :disabled="!hasProgressDownloads">
          <i class="el-icon-video-pause"></i> 批量暂停
        </el-button>
        <el-button class="batch-btn batch-cancel" size="small" @click="cancelSelectedDownloads" :disabled="!hasCheckedItems">
          <i class="el-icon-close"></i> 批量取消
        </el-button>
      </div>
    </div>
    
    <el-table 
      v-loading="loading" 
      :data="downloadRecords" 
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="文件名称" min-width="200">
        <template #default="scope">
          <div class="file-name-cell">
            <el-icon v-if="scope.row.type === 'folder'"><Folder /></el-icon>
            <el-icon v-else-if="scope.row.type === 'image'"><Picture /></el-icon>
            <el-icon v-else-if="scope.row.type === 'video'"><VideoPlay /></el-icon>
            <el-icon v-else-if="scope.row.type === 'audio'"><Headset /></el-icon>
            <el-icon v-else><Document /></el-icon>
            <span>{{ scope.row.name }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="size" label="文件大小" width="100" />
      <el-table-column prop="date" label="下载时间" width="160" />
      <el-table-column label="下载进度" width="180">
        <template #default="scope">
          <el-progress 
            :percentage="getDownloadPercentage(scope.row)" 
            :status="getProgressStatus(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button v-if="scope.row.status === 'failed'" link type="primary" size="small" @click="retryDownload(scope.row)">重新下载</el-button>
          <el-button v-if="scope.row.status === 'progress'" link type="warning" size="small" @click="pauseDownload(scope.row)">暂停下载</el-button>
          <el-button v-if="scope.row.status === 'paused'" link type="primary" size="small" @click="resumeDownload(scope.row)">继续下载</el-button>
          <el-button v-if="scope.row.status === 'progress' || scope.row.status === 'paused'" link type="danger" size="small" @click="cancelDownload(scope.row)">取消</el-button>
          <el-button v-if="scope.row.status !== 'progress'" link type="danger" size="small" @click="deleteRecord(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <div class="total-info">共56条</div>
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        layout="sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <div class="page-goto">
        <span>跳至</span>
        <el-input v-model="jumpPage" size="small" @keyup.enter="handleJumpPage" />
        <span>页</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, Folder, Picture, VideoPlay, Headset, CaretRight, VideoPause, Close } from '@element-plus/icons-vue'

// 记录筛选
const downloadStatus = ref('progress')
const loading = ref(false)
const jumpPage = ref('')
const selectedRows = ref([])

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 下载记录数据
const downloadRecords = ref([])

// 计算下载中和下载完成的数量
const progressCount = ref(10) // 默认值
const finishedCount = ref(9) // 默认值

// 计算属性：是否有正在下载的文件
const hasProgressDownloads = computed(() => {
  return downloadRecords.value.some(record => record.status === 'progress')
})

// 计算属性：是否有选中的项目
const hasCheckedItems = computed(() => {
  return selectedRows.value.length > 0
})

// 处理选择变更
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 获取下载百分比
const getDownloadPercentage = (record) => {
  if (record.status === 'success') return 100
  if (record.status === 'failed') return 0
  
  // 模拟进度数据，实际项目中应该从记录中获取
  if (record.status === 'progress') {
    return record.id * 10 // 示例进度
  }
  
  if (record.status === 'paused') {
    return record.id * 8 // 示例进度
  }
  
  return 0
}

// 获取进度条状态
const getProgressStatus = (record) => {
  if (record.status === 'success') return 'success'
  if (record.status === 'failed') return 'exception'
  if (record.status === 'paused') return 'warning'
  return ''
}

// 加载下载记录
const loadDownloadRecords = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟数据
    const mockData = [
      { id: 1, name: '项目进度.pptx', type: 'document', size: '12.8MB', date: '2023-05-18 16:40:22', status: 'success', speed: '3.1MB/s' },
      { id: 2, name: '客户资料.pdf', type: 'document', size: '5.3MB', date: '2023-05-17 13:25:18', status: 'success', speed: '2.7MB/s' },
      { id: 3, name: '产品样本图.png', type: 'image', size: '6.5MB', date: '2023-05-17 11:05:30', status: 'success', speed: '2.2MB/s' },
      { id: 4, name: '培训材料.zip', type: 'document', size: '45.7MB', date: '2023-05-16 14:30:15', status: 'failed', speed: '0KB/s' },
      { id: 5, name: '市场分析.docx', type: 'document', size: '2.1MB', date: '2023-05-15 10:12:45', status: 'progress', speed: '980KB/s' },
      { id: 6, name: '研发文档.pdf', type: 'document', size: '8.3MB', date: '2023-05-14 09:25:18', status: 'paused', speed: '0KB/s' }
    ]
    
    downloadRecords.value = mockData
    pagination.total = 56 // 模拟总记录数
    
    // 更新计数
    progressCount.value = 10 // 实际项目中应该从API获取
    finishedCount.value = 9 // 实际项目中应该从API获取
  } catch (error) {
    console.error('获取下载记录失败', error)
    ElMessage.error('获取下载记录失败')
  } finally {
    loading.value = false
  }
}

// 分页事件处理
const handleSizeChange = (size) => {
  pagination.size = size
  loadDownloadRecords()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadDownloadRecords()
}

// 跳转到指定页
const handleJumpPage = () => {
  const page = parseInt(jumpPage.value)
  if (page && page > 0 && page <= Math.ceil(pagination.total / pagination.size)) {
    pagination.current = page
    loadDownloadRecords()
  } else {
    ElMessage.warning('请输入有效的页码')
  }
  jumpPage.value = ''
}

// 状态切换
const handleStatusChange = () => {
  pagination.current = 1 // 切换状态时重置到第一页
  loadDownloadRecords()
}

// 暂停单个下载
const pauseDownload = async (record) => {
  try {
    // 实际项目中应该调用暂停API
    // await pauseDownload({ fileName: record.name })
    ElMessage.success(`已暂停下载: ${record.name}`)
    loadDownloadRecords()
  } catch (error) {
    console.error('暂停下载失败', error)
    ElMessage.error('暂停下载失败')
  }
}

// 继续单个下载
const resumeDownload = async (record) => {
  try {
    // 实际项目中应该调用继续API
    // await resumeDownload({ fileName: record.name })
    ElMessage.success(`已继续下载: ${record.name}`)
    loadDownloadRecords()
  } catch (error) {
    console.error('继续下载失败', error)
    ElMessage.error('继续下载失败')
  }
}

// 取消单个下载
const cancelDownload = (record) => {
  ElMessageBox.confirm(`确定要取消 ${record.name} 的下载吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实际项目中应该调用取消API
    // cancelDownloadFile({ fileId: record.id })
    ElMessage.success(`已取消下载: ${record.name}`)
    loadDownloadRecords()
  }).catch(() => {})
}

// 批量取消选中的下载
const cancelSelectedDownloads = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要取消的下载任务')
    return
  }
  
  ElMessageBox.confirm(`确定要取消选中的 ${selectedRows.value.length} 个下载任务吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实际项目中应该调用批量取消API
    // cancelDownloadFiles({ fileIds: selectedRows.value.map(row => row.id) })
    ElMessage.success(`已取消 ${selectedRows.value.length} 个下载任务`)
    loadDownloadRecords()
  }).catch(() => {})
}

// 清空所有下载
const clearAll = () => {
  ElMessageBox.confirm('确定要取消所有下载任务吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实际项目中应该调用清空API
    // clearAllDownloadTasks()
    ElMessage.success('已取消所有下载任务')
    loadDownloadRecords()
  }).catch(() => {})
}

// 全部开始下载
const startAllDownloads = async () => {
  try {
    // 实际项目中应该调用批量开始API
    // await startAllDownloadFiles()
    ElMessage.success('已开始所有下载')
    loadDownloadRecords()
  } catch (error) {
    console.error('开始所有下载失败', error)
    ElMessage.error('开始所有下载失败')
  }
}

// 暂停所有下载
const pauseAllDownloads = async () => {
  try {
    // 实际项目中应该调用批量暂停API
    // await pauseAllDownloadFiles()
    ElMessage.success('已暂停所有下载')
    loadDownloadRecords()
  } catch (error) {
    console.error('暂停所有下载失败', error)
    ElMessage.error('暂停所有下载失败')
  }
}

// 重试下载
const retryDownload = (record) => {
  ElMessage.success(`重新下载文件: ${record.name}`)
  // 实际项目中应该调用重试API
  // retryDownloadFile({ fileId: record.id })
}

// 删除记录
const deleteRecord = (record) => {
  ElMessageBox.confirm(`确定要删除 ${record.name} 的下载记录吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实际项目中应该调用删除API
    // deleteDownloadRecord({ recordId: record.id })
    ElMessage.success('删除成功')
    loadDownloadRecords()
  }).catch(() => {})
}

// 页面加载时获取数据
onMounted(() => {
  loadDownloadRecords()
})
</script>

<style scoped>
.transfer-records {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.record-header {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-bottom: 20px;
  gap: 15px;
}

.tab-container {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  width: 280px;
  position: relative;
}
.tab-item {
  position: relative;
  padding: 8px 15px;
  cursor: pointer;
  text-align: center;
  flex: 1;
  background-color: #fff;
  color: #888;
  transition: all 0.3s;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #e0e0e0;
}

.tab-item.left {
  border-radius: 6px 0 0 6px;
  border-right: none;
}

.tab-item.right {
  border-radius: 0 6px 6px 0;
}

.tab-item.active {
  color: #6c9efc;
  border-color: #6c9efc;
  z-index: 1;
}

/* 当左侧激活时，确保右侧标签页的左边框为蓝色 */
.tab-item.left.active + .tab-item.right {
  border-left-color: #6c9efc;
}

/* 当右侧激活时，确保左侧标签页的右边框为蓝色 */
.tab-item.right.active {
  border-left-color: #6c9efc;
}

.action-buttons {
  display: flex;
  gap: 12px;
  margin-top: 8px;
}

.batch-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 6px 16px;
  border-radius: 4px;
  font-weight: normal;
  font-size: 14px;
  transition: all 0.2s;
  border: none;
}

.batch-start {
  background-color: #6c9efc;
  color: white;
}

.batch-start:hover:not(:disabled) {
  background-color: #5a8ae6;
}

.batch-pause {
  background-color: #f0ad4e;
  color: white;
}

.batch-pause:hover:not(:disabled) {
  background-color: #ec971f;
}

.batch-cancel {
  background-color: #f77b7b;
  color: white;
}

.batch-cancel:hover:not(:disabled) {
  background-color: #f55a5a;
}

.batch-btn i {
  margin-right: 4px;
  font-size: 14px;
}

.file-name-cell {
  display: flex;
  align-items: center;
}

.file-name-cell span {
  margin-left: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-info {
  color: #606266;
  font-size: 14px;
}

.page-goto {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #606266;
  font-size: 14px;
}

.page-goto .el-input {
  width: 50px;
  margin: 0 5px;
}

@media screen and (max-width: 768px) {
  .record-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .tab-filter, .action-buttons {
    width: 100%;
  }
  
  .action-buttons {
    justify-content: space-between;
  }
  
  .pagination-container {
    flex-direction: column;
    align-items: center;
    gap: 10px;
  }
}
</style> 